/* File : blockmap.c */

#include "blockmap.h"

int getbit(Tbyte Byte, int n){
	switch(n){
		case 0: return Byte.bits.bit0;
		case 1: return Byte.bits.bit1;
		case 2: return Byte.bits.bit2;
		case 3: return Byte.bits.bit3;
		case 4: return Byte.bits.bit4;
		case 5: return Byte.bits.bit5;
		case 6: return Byte.bits.bit6;
		case 7: return Byte.bits.bit7;
	}
}

void setbit(Tbyte* Byte, int n, unsigned int value){
	switch(n){
		case 0: Byte->bits.bit0 = value;
		break;
		case 1: Byte->bits.bit1 = value;
		break;
		case 2: Byte->bits.bit2 = value;
		break;
		case 3: Byte->bits.bit3 = value;
		break;
		case 4: Byte->bits.bit4 = value;
		break;
		case 5: Byte->bits.bit5 = value;
		break;
		case 6: Byte->bits.bit6 = value;
		break;
		case 7: Byte->bits.bit7 = value;
		break;
	}
}


void initBlockmap(FILE* fs, Tblockmap* Tb){
	int i;
	char* string = (char*) malloc(125001);	
	fseek(fs,4000,SEEK_SET);
	fgets(string,125000,fs);	
	for(i = 0; i < 125000; i++){
		(*Tb)[i].val = string[i];
	}
}

void fillBlocknum(FILE* fs, Tblockmap* Tb, int blocknum){
	int i;
	int charnum = blocknum/8;
	int offset = blocknum%8;
	setbit((&(*Tb)[charnum]),offset,1);
	fseek(fs,4000,SEEK_SET);
	for(i = 0; i < 125000; i++){
		putc((*Tb)[i].val,fs);
	}
}

void releaseBlocknum(FILE* fs, Tblockmap* Tb, int blocknum){
	int i;
	int charnum = blocknum/8;
	int offset = blocknum%8;
	setbit((&(*Tb)[charnum]),offset,0);
	fseek(fs,4000,SEEK_SET);
	for(i = 0; i < 125000; i++){
		putc((*Tb)[i].val,fs);
	}
}

int getBlocknum(Tblockmap Tb, int blocknum){
	int charnum = blocknum/8;
	int offset = blocknum%8;
	return getbit(Tb[charnum],offset);
}

int countFilledBlock(Tblockmap Tb, int Max){
	int i;
	int count = 0;
	for(i = 0; i < Max; i++){
		if(getBlocknum(Tb,i))
			count++;
	}
	return count;
}

int countBlankBlock(Tblockmap Tb, int Max){
	return Max - countFilledBlock(Tb,Max);
}
